/**
 * @Date 2023-02-21 14:00:07
 * @Remark
 */

// lib
// import moment from "moment";
// config
// script & methods & public
import toast from "components/toast";
// import timeUtils from "utils/timeUtils";

// store
import { state } from "./state";
// service
import {
  addCategoryService,
  deleteProCategoryService,
  editProCategoryService,
  getCategoryLongPageService,
  getCategoryPageService,
} from "biz/Books/service";
import { ReqCategoryPage } from "biz/Books/api";
// interface

export async function getCategoryPage() {
  const sp = state.getSearch();
  const params: ReqCategoryPage = {
    pageNum: state.page,
    pageSize: state.size,
    ...sp,
  };
  state.loading = true;
  const result = await getCategoryPageService(params);
  state.loading = false;
  if (result.payload) {
    state.total = result.payload.total;
    state.list = result.payload.list;
  }
}

export async function addCategory(form: any) {
  const params: ReqCategoryPage = {
    ...form,
  };
  state.editModalLoading = true;
  const result = await addCategoryService(params);
  state.editModalLoading = false;
  if (result.payload) {
    toast.success("添加成功");
    state.editModal = false;
    getCategoryPage();
  }
}

export async function updateCategory(form: any, categoryId: number) {

  // 调用服务
  state.editModalLoading = true;
  const result = await editProCategoryService({
    categoryId,
    ...form,
  });
  state.editModalLoading = false;
  // 成功
  if (result.payload) {
    toast.success("编辑成功");
    state.editModal = false;
    getCategoryPage();
  }
}
// 不分页列表
export async function getCategoryLongPage() {
  state.loading = true;
  const result = await getCategoryLongPageService({});
  state.loading = false;
  if (result.payload) {
    state.longList = result.payload.filter(
      (item: any) => item.parentCategoryId === null,
    );
  }
}

export async function delProCategory(id: number) {
  const result = await deleteProCategoryService({ categoryId: id });
  if (result.payload) {
    toast.success("删除成功");
    state.setSearch();
    getCategoryPage();
  }
}

export async function didMount() {
  getCategoryPage();
  getCategoryLongPage();
}
